﻿using UnityEditor;
using UnityEngine;
using Directory = System.IO.Directory;

namespace EditorExtension
{
    
    public class ProjectExample
    {
        private const string PATH = "EditorExtensions/02_IMGUI/04_Enable Custom Project";
        private static bool mCustomProjectEnabled = false;
        
        static ProjectExample()
        {
            Menu.SetChecked(PATH, mCustomProjectEnabled);
        }

        [MenuItem(PATH)]
        static void Enable()
        {
            mCustomProjectEnabled = !mCustomProjectEnabled;
            if (mCustomProjectEnabled)
            {
                RegisterProject();
            }
            else
            {
                UnRegisterProject();
            }
            
            Menu.SetChecked(PATH, mCustomProjectEnabled);
            
            // 重新绘制
            EditorApplication.RepaintProjectWindow();
        }
        
        static void RegisterProject()
        {
            EditorApplication.projectWindowItemOnGUI += OnProjectGUI;
            EditorApplication.projectChanged += OnProjectChanged;
        }

        private static void OnProjectChanged()
        {
            Debug.Log("Project Changed");
        }

        private static void OnProjectGUI(string guid, Rect selectionRect)
        {
            string assetPath = AssetDatabase.GUIDToAssetPath(guid);
            string[] files = Directory.GetFiles(assetPath);
            
            Rect countLabelRect = selectionRect;
            countLabelRect.x += 150;
            GUI.Label(countLabelRect, files.Length.ToString());
        }

        static void UnRegisterProject()
        {
            EditorApplication.projectWindowItemOnGUI -= OnProjectGUI;
            EditorApplication.projectChanged -= OnProjectChanged;
        }
    }
}